﻿//------------------------------------------------------------------------------
// <copyright file="BuildNupkg_NetFrameworkCommand.cs" company="Microsoft">
//     Copyright (c) Microsoft.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------

using System;
using System.ComponentModel.Design;
using System.Globalization;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using EnvDTE;
using EntitiesGenerator.Utils;
using System.Reflection;
using System.IO;

namespace EntitiesGenerator
{
    /// <summary>
    /// Command handler
    /// </summary>
    internal sealed class BuildNupkg_NetFrameworkCommand
    {
        /// <summary>
        /// Command ID.
        /// </summary>
        public const int CommandId = 256;

        /// <summary>
        /// Command menu group (command set GUID).
        /// </summary>
        public static readonly Guid CommandSet = new Guid("dc205adc-086b-46ac-b362-eff723fa8ba1");

        /// <summary>
        /// VS Package that provides this command, not null.
        /// </summary>
        private readonly Package package;


        /// <summary>
        /// Initializes a new instance of the <see cref="BuildNupkg_NetFrameworkCommand"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        private BuildNupkg_NetFrameworkCommand(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            this.package = package;

            OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (commandService != null)
            {
                var menuCommandID = new CommandID(CommandSet, CommandId);
                var menuItem = new MenuCommand(this.MenuItemCallback, menuCommandID);
                commandService.AddCommand(menuItem);
            }
        }

        /// <summary>
        /// Gets the instance of the command.
        /// </summary>
        public static BuildNupkg_NetFrameworkCommand Instance
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the service provider from the owner package.
        /// </summary>
        private IServiceProvider ServiceProvider
        {
            get
            {
                return this.package;
            }
        }

        /// <summary>
        /// Initializes the singleton instance of the command.
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        public static void Initialize(Package package)
        {
            Instance = new BuildNupkg_NetFrameworkCommand(package);
        }

        /// <summary>
        /// This function is the callback used to execute the command when the menu item is clicked.
        /// See the constructor to see how the menu item is associated with this function using
        /// OleMenuCommandService service and MenuCommand class.
        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="e">Event args.</param>
        private async void MenuItemCallback(object sender, EventArgs e)
        {
            var dte = (DTE)this.ServiceProvider.GetService(typeof(SDTE));
            if (dte == null)
            {
                this.ServiceProvider.Show("获取服务失败!");
                return;
            }

            await Build(dte);
        }

        private async System.Threading.Tasks.Task Build(DTE dte)
        {
            string nugetPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "nuget.exe");

            foreach (SelectedItem item in dte.SelectedItems)
            {
                string csprojFullName = item.Project.FullName;
                string binDir = Path.Combine(Path.GetDirectoryName(csprojFullName), "bin");

                try
                {
                    if (!Directory.Exists(binDir))
                        Directory.CreateDirectory(binDir);

                    dte.OutputMsg($"开始为项目:[{csprojFullName}]创建nupkg包!");
                    ///p:IncludeSymbols=true
                    string command = $"{nugetPath} pack \"{csprojFullName}\" -OutputDirectory \"{binDir}\" -Properties Configuration=Release";
                    string result = await Cmd.ExecuteAsync(command);
                    dte.OutputMsg(result);
                    dte.OutputMsg($"创建Nupkg包完成,现在你可以所用发布功能发布你的库了!");
                }
                catch (Exception ex)
                {
                    dte.OutputMsg($"[{csprojFullName}]创建发生错误:{ex.Message}!");
                }
            }
        }
    }
}
